import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from '@nestjs/common';

@Catch()
export class HttpExceptionFilter<T> implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    if (exception.name === 'QueryFailedError') {
      //数据库操作报错统一处理
      response.status(HttpStatus.INTERNAL_SERVER_ERROR).send({
        message: exception.message,
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        url: request.originalUrl,
      });
    } else if (exception instanceof HttpException) {
      //内置错误处理
      response.status(exception.getStatus()).send({
        message: exception.message,
        code: exception.getStatus(),
        url: request.originalUrl,
      });
    } else {
      console.log(exception);
      response.status(HttpStatus.INTERNAL_SERVER_ERROR).send({
        message: '未知错误',
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        url: request.originalUrl,
      });
    }
  }
}
